<template>
  <el-input
    v-model="inputValue"
    v-bind="attrs"
    style="width: 200px; height: 32px"
    @compositionstart="handleCompositionStart"
    @compositionend="handleCompositionEnd"
    @input="handleInput"
    @keyup.enter="$emit('keyup-enter', $event)"
    clearable
  />
</template>

<script setup>
import { ref, watch, onBeforeUnmount, useAttrs } from "vue";
import { debounce } from "lodash-es";

const props = defineProps({
  modelValue: { type: [String, Number], default: "" },
  // 防抖时间（毫秒）
  debounceTime: { type: Number, default: 300 },
  // 是否启用防抖
  debounce: { type: Boolean, default: true },
  // 是否在输入法组合结束时立即触发
  triggerOnCompositionEnd: { type: Boolean, default: true },
});

const emit = defineEmits(["update:modelValue", "submit", 'keyup-enter']);

const attrs = useAttrs();
const inputValue = ref(props.modelValue);
const isComposing = ref(false);

// 防抖处理函数
const debouncedEmit = debounce((value) => {
  emit("submit", value);
}, props.debounceTime);

// 清理防抖函数
onBeforeUnmount(() => {
  debouncedEmit.cancel();
});

// 输入法开始组合
const handleCompositionStart = () => {
  isComposing.value = true;
};

// 输入法结束组合
const handleCompositionEnd = (e) => {
  isComposing.value = false;
  if (props.triggerOnCompositionEnd) {
    submitHandler(e.target.value);
  }
};

// 实际提交处理
const submitHandler = (value) => {
  if (props.debounce) {
    debouncedEmit(value);
  } else {
    emit("submit", value);
  }
};

// 输入事件处理
const handleInput = (value) => {
  // 同步 v-model
  emit("update:modelValue", value);

  // 非组合状态立即处理
  if (!isComposing.value) {
    submitHandler(value);
  }
};

// 监听外部 modelValue 变化
watch(
  () => props.modelValue,
  (val) => {
    inputValue.value = val;
  }
);
</script>
